package net.gd.server;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.Date;
import java.util.Vector;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;

import net.gd.servlet.ModelInfoServlet;
import net.gd.servlet.PermissionServlet;
import net.gd.servlet.UdfInfoServlet;
import net.gd.utils.ApplicationConf;
import net.gd.utils.CustomizeSpringContext;
import net.gd.utils.DateUtils;

public class CustomizeStart {
	
	public static void main(String[] args) throws Exception {
		CustomizeStart main = (CustomizeStart) CustomizeSpringContext.getBean(CustomizeStart.class);
		main.startServer();
	}
	
	public void startServer() throws Exception {
		Logger.getLogger("org").setLevel(Level.ERROR);
		Server server = new Server(Integer.valueOf(ApplicationConf.getProperty("abdCustomize.port")));
		server.setHandler(new DefaultHandler());
		WebAppContext webContext = new WebAppContext();
		Vector<URL> secondayClassPathURLVector = new Vector<>();
		URL[] existingURLs = ((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURLs();
		System.out.println(DateUtils.getDateTimeNow()+ " INFO " + "打印依赖Jar文件路径：");
		for (URL parentURL : existingURLs) {
			System.out.println(parentURL);
		}
		ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader().getParent();
		URL[] existingURLs1 = ((URLClassLoader) parentClassLoader).getURLs();
		for (URL parentURL : existingURLs1) {
			System.out.println(parentURL);
		}
		// use our class path entries to create a parent for the
		// webappclassloader that knows how to use or referenced class paths
		URLClassLoader internalClassPathUrlClassLoader = new URLClassLoader(
				secondayClassPathURLVector.toArray(new URL[secondayClassPathURLVector.size()]), parentClassLoader);
		// this is the point.
		// webContext.setClassLoader(internalClassPathUrlClassLoader); // this
		// is the point.
		webContext.setContextPath("/abd");
		webContext.setDescriptor(ApplicationConf.getProperty("abd.web.xml.path"));
		webContext.setResourceBase(ApplicationConf.getProperty("abd.web.path"));
		webContext.setResourceBase("testwebpage");  // 打开注释可以访问测试api页面
		webContext.setParentLoaderPriority(true);
		webContext.addServlet(new ServletHolder(new PermissionServlet()), "/permission/*");
		webContext.addServlet(new ServletHolder((ModelInfoServlet)CustomizeSpringContext.getBean(ModelInfoServlet.class)), "/model/*");
		webContext.addServlet(new ServletHolder((UdfInfoServlet)CustomizeSpringContext.getBean(UdfInfoServlet.class)), "/udf/*");
		System.out.println(webContext.getContextPath());

		server.setHandler(webContext);
		server.start();
		server.join();
	}
	
}
